<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------


/**
 * 微信客服处理类
 *
 * @package  htdocs
 * @subpackage  module/base
 * @create by allen.qiang
 * @version 1.0
 */

quanli_require('module/extend/messageManager.class.php');

class serviceHandler {

    private $dbca;

    private $cacheObj;
    
    public function __construct( $dbca ) {
    	
        $this->dbca = $dbca;
        
        $this->cacheObj = new Redis();
        
        $this->cacheObj->connect(CACHE_REDIS_ADDR,CACHE_REDIS_PORT);
        
    }

    /**
     * 查询公众号信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchWxPublic( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //流水号
        if ( isset($arg_array['wxID']) && is_numeric($arg_array['wxID']) ) {
            $sql .= ' AND wxID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['wxID'];
        }

        //微信号
        if ( isset($arg_array['wxNo']) && !empty($arg_array['wxNo']) ) {
            $sql .= ' AND wxNo = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['wxNo'];
        }

        //公众号原始ID
        if ( isset($arg_array['originalID']) && !empty($arg_array['originalID']) ) {
            $sql .= ' AND originalID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['originalID'];
        }


        //公众号名称
        if ( isset($arg_array['wxName']) && !empty($arg_array['wxName']) ) {
            $sql .= ' AND wxName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['wxName'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_wx_public ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT * FROM wechat_wx_public ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'wxID' 	                      => $item->wxID,
                    'originalID'                 => $item->originalID,
                    'wxNo' 	                      => $item->wxNo,
                    'wxName' 	                  => $item->wxName,
                    'wxToken' 	                  => $item->wxToken,
                    'wxAPPID' 	                  => $item->wxAPPID,
                    'wxAPPSECRET' 	              => $item->wxAPPSECRET,
                    'publicSeatLimitNumber' 	  => $item->publicSeatLimitNumber,
                    'publicAllocatedNumber' 	  => $item->publicAllocatedNumber,
                    'useFlg' 	                  => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存公众号信息
     */
    public function saveWechatPublic( $arg_array ){

        if( !isset( $arg_array['wxNo'] , $arg_array['wxName'] , $arg_array['originalID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        if( empty( $arg_array['originalID'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入原始ID' );
        }

        if( empty( $arg_array['wxNo'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入微信号' );
        }

        if( empty( $arg_array['wxName'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入公众号名称' );
        }

        //接收参数
        $wxNo       = trim( $arg_array['wxNo'] );
        $originalID = trim( $arg_array['originalID'] );
        $wxName     = trim( $arg_array['wxName'] );

        if( !isset($arg_array['wxID']) || $arg_array['wxID'] == 0 || !is_numeric($arg_array['wxID']) ){
            $arg_array['wxID'] = 0;
        }

        try{

            /********************** 检查微信号是否重复 ***********************/
            //查询"微信号"是否重复
            if( $arg_array['wxID'] > 0 ){
                $check_sql = 'SELECT * FROM wechat_wx_public WHERE wxID <> ? AND wxNo=?';
                $check_result = $this->dbca->stmt_query($check_sql,'is',array($arg_array['wxID'],$wxNo) );
            } else {
                $check_sql = 'SELECT * FROM wechat_wx_public WHERE wxNo=?';
                $check_result = $this->dbca->stmt_query($check_sql,'s',$wxNo);
            }

            //检查该"微信号"是否已经存在
            if( $check_result ){
                return ( array('message'=>'微信号重复' , 'code'=>400 ) );
            }

            //保存和更新公众号信息
            $wechat_wx_public = new entity('wechat_wx_public');

            if( $arg_array['wxID'] > 0 ){

                $wechat_wx_public->wxID	= $arg_array['wxID'];

                if( !$this->dbca->fetch($wechat_wx_public) ){
                    return array( 'code'=>404 , 'message'=>'没有找到信息' );
                }

            } else {
                $wechat_wx_public->creator	= $arg_array['operator'];
            }

            $wechat_wx_public->wxNo  	    = $wxNo;
            $wechat_wx_public->originalID   = $originalID;
            $wechat_wx_public->wxName	    = $wxName;
            $wechat_wx_public->wxToken	    = isset($arg_array['wxToken'])?$arg_array['wxToken']:'';
            $wechat_wx_public->wxAPPID	    = isset($arg_array['wxAPPID'])?$arg_array['wxAPPID']:'';
            $wechat_wx_public->wxAPPSECRET = isset($arg_array['wxAPPSECRET'])?$arg_array['wxAPPSECRET']:'';
            $wechat_wx_public->useFlg       = $arg_array['useFlg'];

            $this->dbca->save( $wechat_wx_public ) ;

            if( $arg_array['wxID'] == 0 ){
                $arg_array['wxID'] = $this->dbca->insert_id;
            }

            return array( 'code' => 200, 'message' => '保存成功' , 'data'=>$arg_array['wxID'] );

        }catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array('code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                error_log( $e->getMessage() );
                return array('code' => 500, 'message' => '系统错误，保存失败' );
            }

        }

    }

    //删除公共号
    public function deletePublic(&$arg_array){

        if(!isset($arg_array['delArr'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        //统计不存在的信息的数目
        $errorNum = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        //检查要删除的信息是否全部存在
        foreach( $arg_array['delArr'] as $val ){

            //检查信息是否存在
            $check_obj = new entity('wechat_wx_public');
            $check_obj->wxID = $val;

            if( !$this->dbca->fetch( $check_obj ) )
                $errorNum++;
            $deleteObjArr[] = $check_obj;

        }

        if( $errorNum > 0 ){

            return array('message'=>'所选公众号部分已不存在，请刷新页面' , 'code'=>400 );

        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $delobj ){
                $this->dbca->delete( $delobj );
            }

            //提交事务
            $this->dbca->commit();

            return array('code'=>200,'message'=>'删除成功');

        }catch(Exception $e){
            //回滚事务
            $this->dbca->rollBack();

            error_log($e->getMessage());
            return null;
        }

    }

    //修改公众号使用状态
    public function changePublicFlg(&$arg_array){

        if(!isset($arg_array['wxID'])||!isset($arg_array['useFlg'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            //查询公众号
            $public = new entity('wechat_wx_public');
            $public->wxID = $arg_array['wxID'];
            if (!$this->dbca->fetch($public)) {
                return array('code'=>404,'message'=>'公众号未找到');
            }

            //修改付款方式使用状态
            $useFlg = $public->useFlg;
            if ($useFlg ==1) {

                if($arg_array['useFlg'] == 0){
                    $public->useFlg = 0;
                }else{
                    return array('code'=>400,'message'=>'公众号已处于启用状态');
                }

            } else {

                if($arg_array['useFlg'] == 1){
                    $public->useFlg = 1;
                }else{
                    return array('code'=>400,'message'=>'公众号已处于禁用状态');
                }

            }
            $this->dbca->save($public);

            if ($useFlg == 1) {
                return array( 'code' => 200, 'message' => '公众号禁用成功' );
            } else {
                return array( 'code' => 200, 'message' => '公众号启用成功' );
            }


        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 检查是否分配了坐席
     */
    public function checkServiceSeat($arg_array,$G_PGLOB){

        if( !isset($arg_array['wxID']) || !is_numeric($arg_array['wxID']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //获取当前登录用户的userID
        $userID = $G_PGLOB->currentUserID;

        //获取公众号坐席分配信息

        $getUserSeatInfo = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'],true);

        if (!empty($getUserSeatInfo)) {
            if( in_array( $userID , $getUserSeatInfo) ){

                //获取该用户坐席号
                $seatInfo = array_keys( $getUserSeatInfo , $userID );

                if( isset($arg_array['seatID']) && !empty($arg_array['seatID']) ){

                    //坐席号有误
                    if( $arg_array['seatID'] != $seatInfo[0] ){

                        return array( 'code' => 402 , 'message' => '坐席号有误' , 'data'=>$seatInfo[0] );

                    }

                }

                return array( 'code' => 200 , 'message' => 'ok' , 'data'=>$seatInfo[0] );

            } else {
                return array( 'code' => 404, 'message' => '没有找到坐席信息' );
            }
        } else {
            return array( 'code' => 404, 'message' => '没有找到坐席信息' );
        }

    }

    /**
     *  给客服分配坐席
     *
     * $arg_array = array(
     *  'pcustID'  //当前登录用户的pcustID
     * )
     */
    public function giveSeatToService($arg_array,$G_PGLOB){

        if( !isset( $arg_array['wxID'],$G_PGLOB) || !is_numeric($arg_array['wxID']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //检查客服坐席信息
        $check_array = array(
            'wxID'   => $arg_array['wxID']
        );
        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB);

        if( $check_result['code'] == 200 || $check_result['code'] == 402 ){
            return array( 'code' => 200 , 'data' => $check_result['data'] );
        }

        //获取当前登录用户的userID
        $userID = $G_PGLOB->currentUserID;

        //获取坐席号（UUID）
        $seatID = make_uuid();

        try{

            //更新公众号已分配坐席信息
            $wechat_wx_public = new entity('wechat_wx_public');
            $wechat_wx_public->wxID = $arg_array['wxID'];
            if( !$this->dbca->fetch( $wechat_wx_public ) ){
                return array( 'code'=> 404 , 'message' => '公众号信息没找到');
            }

            $wechat_wx_public->publicAllocatedNumber = $wechat_wx_public->publicAllocatedNumber+1;

            //保存坐席与客服映射关系
            $wechat_seat_service_map = new entity('wechat_seat_service_map');
            $wechat_seat_service_map->creator  = $userID;
            $wechat_seat_service_map->wxID     = $arg_array['wxID'];
            $wechat_seat_service_map->seatID   = $seatID;
            $wechat_seat_service_map->pcustID  = $userID;
            $wechat_seat_service_map->custName = $G_PGLOB->currentUserName;

            //保存坐席分配记录日志
            $wechat_seat_log = new entity('wechat_seat_log');
            $wechat_seat_log->creator = $userID;
            $wechat_seat_log->wxID    = $arg_array['wxID'];
            $wechat_seat_log->seatID  = $seatID;
            $wechat_seat_log->pcustID = $userID;

            //开启事务
            $this->dbca->beginTransaction();

            //更新公众号“已分配坐席数量”字段
            $this->dbca->save($wechat_wx_public);

            //查询坐席数量是否已经超出
            $temp_array = array(
                'wxID' => $arg_array['wxID']  //公众号ID
            );
            $getPublicInfo = $this->searchWxPublic($temp_array);

            if( $getPublicInfo[0]['publicAllocatedNumber'] > $getPublicInfo[0]['publicSeatLimitNumber'] ){
                throw new Exception('客服已满，请稍候再试',400);
            }

            $this->dbca->save($wechat_seat_service_map);

            $this->dbca->save($wechat_seat_log);

            //提交事务
            $this->dbca->commit();

            //保存公众号坐席与客服映射关系
            $getUserSeatInfo = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'],true);
            $getUserSeatInfo[$seatID] = $userID;
            $G_PGLOB->sessionCache_set('__cs_seatList_'.$arg_array['wxID'],$getUserSeatInfo,86400,true);

            //生成该坐席信息
            $seat_info = array(
                'messageList' => array(),
                'recvMessageNumber' => 0,
                'lastRecvTimeStamp' => '',
                'customeID' => $userID
            );
            //$G_PGLOB->sessionCache_set('recvMessageList_'.$arg_array['wxID'].'_'.$seatID,$seat_info,86400,true);

            //生成坐席状态信息结构
            $seat_check = array(
                'messageRecvNumber' => 0,    //当前坐席接收到的消息数
                'messageReadNumber' => 0,    //当前坐席读取到的消息数
                'messageWriteNumber' =>0,    //当前坐席回复的消息数
                'lastRecvTimeStamp' => 0,   //当前坐席接收上一次消息的时间戳
                'lastReadTimeStamp' => 0,   //当前坐席读取上一次的时间戳
                'lastWriteTimeStamp' => 0,  //当前坐席回复上一次的时间戳
                'status' => messageManager::SEAT_LOGIN,                 //坐席状态 0:已退出 1:已登录可以接收消息 2:繁忙 4:空闲 5:超时 6:无响应 7:离开  8:锁定
                'lockTimeStamp' => 0,          //锁定时间戳，如果锁定时间大于5s,则修改其状态为正常
                'rate' => 0,                     //信息百分比
                'seatCode' => '',
                'useFlg' => 1,
            	'userNumber' =>0,
            );
            
            $messageManagerObj=new messageManager($arg_array['wxID'],$seatID);
            $messageManagerObj->init($this->cacheObj);
            $messageManagerObj->setSeatStatsT($seat_check,messageManager::STATS_MESSAGE_EXPIRE);
			
            $readMessageParams=array(  
            		'wxID'   => $arg_array['wxID'],		//公众号ID
            		'seatID' => $seatID,				//坐席ID
            		'isLogin'=> True 					//客服登录坐席
            );
            
            $messageList=$this->getSeatMessage($readMessageParams,$G_PGLOB);
            
            return array( 'code'=> 200 , 'message' => 'ok', 'data' => $seatID );

        }catch (Exception $e){

            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 获取用户历史消息
     *
     * $arg_array = array(
     *      'uuidArray' => array(uuid,uuid,...),
     *      'wxID' => 1,
     *      'seatID' => '29C5F5B194499B307A85BB5DA6D0A330'
     *  );
     */
    public function getHistoryMessage($arg_array,$G_PGLOB){

        if( !isset($arg_array['uuidArray'],$arg_array['wxID'],$arg_array['seatID']) || empty($arg_array['seatID']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //检查客服坐席信息
        $check_array = array(
            'seatID' => $arg_array['seatID'],
            'wxID'   => $arg_array['wxID']
        );
        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB);

        if( $check_result['code'] != 200 ){
            return array( 'code' => $check_result['code'] , 'message' => $check_result['message'] );
        }

        //获取坐席状态信息
        $seatStatusMessage = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'].'_'.$arg_array['seatID'],true);

        

        $messageObj=new messageManager($arg_array['wxID'],$arg_array['seatID']);
        $messageObj->init($this->cacheObj);
        $result = $messageObj->readHistoryMessage($arg_array['uuidArray']);

        return array( 'code' => 400, 'message' => 'ok' , 'data'=>$result , 'status'=>$seatStatusMessage['status'] );

    }

    /**
     *  获取坐席消息
     *
     * $arg_array = array(
     * 'seatID' => 'fsdfsad9897685sdnfjsd'  //客服坐席号(UUID)
     * 'wxID' => 'fsdfsad9897685sdnfjsd'    //公众号ID
     * "isLogin" => True 					//是否是登录操作
     * )
     */
    public function getSeatMessage($arg_array,$G_PGLOB){
        
        if( !isset($arg_array['seatID'],$arg_array['wxID']) || empty($arg_array['seatID']) || !is_numeric($arg_array['wxID']) ){
            return array( 'code' => 400, 'message' => '参数错误','data'=>'ajax' );
        }

        $isLogin=False;
        
        if (isset($arg_array['isLogin']) && $arg_array['isLogin'] == 1 ){
        	$isLogin=True;
        }
        //检查客服坐席信息
        $check_array = array(
            'seatID' => $arg_array['seatID'],
            'wxID'   => $arg_array['wxID']
        );
        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB);

        if( $check_result['code'] != 200 ){
            return array( 'code' => $check_result['code'] , 'message' => $check_result['message'] );
        }

        //获取坐席状态信息
        $seatStatusMessage = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'].'_'.$arg_array['seatID'],true);

       
        $messageObj=new messageManager($arg_array['wxID'],$arg_array['seatID']);
        $messageObj->init($this->cacheObj);
        
        
        if ($isLogin == True){
       		$result = $messageObj->readMessage(True);
        }
        else {
	        if(isset($arg_array['uuid'])&&!empty($arg_array['uuid'])){

	                $result = $messageObj->readMessage(array($arg_array['uuid']));
	            }else{

	                $result = $messageObj->readMessage();
	            }
        	
        }

        //记录需要更新的日志对象
        $update_array = array();

        if( $result['data']['newMessage'] ){

            foreach ( $result['data']['newMessage'] as $message ){

                foreach ( $message as $updateMsg ) {

                    //更新日志
                    $log_customerservice_message = new entity('log_customerservice_message');
                    $log_customerservice_message->logID = $updateMsg['messageId'];

                    if( !$this->dbca->fetch( $log_customerservice_message ) ){
                        continue;
                    }

                    $log_customerservice_message->messageStatus        = 2;
                    $log_customerservice_message->readMessageTimeStamp = time();

                    $update_array[] = $log_customerservice_message;

                }

            }

        }

        //更新日志状态
        if( $update_array ){

            try{

                //开启事务
                $this->dbca->beginTransaction();

                foreach( $update_array as $updateObj ){
                    $this->dbca->save($updateObj);
                }

                //提交事务
                $this->dbca->commit();

            }catch (Exception $e){

                //回滚事务
                $this->dbca->rollBack();
                error_log( $e->getMessage() );

            }

        }

        return array( 'code'=> 200 , 'message' => 'ok', 'data' => $result , 'status'=>$seatStatusMessage['status'] );

    }

    /**
     *  回复消息
     *
     * $arg_array = array(
     *  'seatID' => '97a1a94896d511e309899001d0f0ef5vj'  //客服坐席号
     *  'wxID' => '1'                                    //公众号ID
     *  'uuid' => '60a1a94896d511e39579001d0f0ef6cb'     //会话客户的UUID
     *  'message' => 'abc'                               //回复内容
     *  'msgID' => '1010'                                //日志ID
     *  'leftMessage' => 5                               //当前会话客户剩余需要回复的消息数量
     * )
     */
    public function replyMessage($arg_array,$G_PGLOB){

        if( !isset( $arg_array['seatID'],$arg_array['wxID'],$arg_array['message'],$arg_array['uuid'])){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if( empty($arg_array['seatID']) || empty($arg_array['wxID']) || empty($arg_array['uuid']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if( empty($arg_array['message']) ){
            return array( 'code' => 400, 'message' => '请输入回复内容' );
        }

        if (!isset($arg_array['messageFlg'])){
            $arg_array['flg']=messageManager::ONLINE;
        }else if($arg_array['messageFlg']==2){
            $arg_array['flg']=messageManager::OFFLINE;
        }

        //传入消息ID进行更新
//        if( !isset($arg_array['msgID']) || !is_numeric($arg_array['msgID']) ){
//            return array( 'code' => 400 , 'message' => '参数错误' );
//        }

        //检查客服坐席信息
        $check_array = array(
            'seatID' => $arg_array['seatID'],
            'wxID'   => $arg_array['wxID']
        );
        $pcustID = $G_PGLOB->currentUserID;

        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB,$pcustID);
        if( $check_result['code'] != 200 ){
            return array( 'code' => $check_result['code'] , 'message' => $check_result['message'] );
        }
        
        $commHandlerObj=new commHandler($G_PGLOB->DBCA);
        $messageId=$commHandlerObj->generate_seqno('seqno_customerservice_log');

        //获取坐席状态信息
        $seatStatusMessage = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'].'_'.$arg_array['seatID'],true);

        //回复信息参数
        $params = array(
        		'messageId' => $messageId,
                'uuid' => $arg_array['uuid'],
	 			'responseMessage' => $arg_array['message'],
	 			'type'	=> 1,
      			'mode' => 2,
                'processMode' => $arg_array['flg'],
        );

       
		
        //更新数据信息
        $messageObj = new messageManager($arg_array['wxID'],$arg_array['seatID']);
        $messageObj->init($this->cacheObj);
        $messageObj->setProcessMessageMode($arg_array['flg']);
        $result = $messageObj->responseMessage( $params );

        if( $result['code'] != 200 ){
            return array( 'code'=> 400 , 'message' => '发送消息失败');
    }

//        //当前会话客户存在需要回复的消息
//        if( $arg_array['leftMessage'] != 0 ){
//
//            $redisObj = new Redis();
//
//            $redisObj->connect(CACHE_REDIS_ADDR,CACHE_REDIS_PORT);
//
//            //更新redis数据
//            $messageObj = new messageManager($arg_array['wxID'],$arg_array['seatID']);
//            $messageObj->init($redisObj);
//            $params = $arg_array['message'];
//            $result = $messageObj->responseMessage($arg_array['uuid'], $params );
//
//        }

        //引入微信公共类
        quanli_include('module/base/wechatHandler.class.php');

        //引入微信高级接口公共类
        quanli_include('weixin/api/wechatAdvancedInterface.class.php');

        //实例化微信公共类
        $wechatHandler = new wechatHandler( $this->dbca );

        //实例化微信高级接口
        $wechatAdvancedInterface = new wechatAdvancedInterface( $G_PGLOB );

        //查询公众号信息
        $public_array = array(
            'wxID' => $arg_array['wxID']
        );
        $getPublicInfo = $this->searchWxPublic($public_array);

        if( empty($getPublicInfo) ){
            return array( 'code'=> 404 , 'message' => '没有找到公众号信息');
        }

        //查询微信用户信息
        $user_array = array(
            'uuid' => $arg_array['uuid']
        );
        $wechat_user_info = $wechatHandler->searchUserList( $user_array );

        if( empty( $wechat_user_info ) ){
            return array( 'code'=> 404 , 'message' => '没有找到客户信息');
        }

        /**
         * 调用回复消息方法
         */
        $reply_array = array(

            array(
                'openid' => $wechat_user_info[0]['openId'],
                'msgType' => 'text',
                'content' => $arg_array['message']
            )

        );


        $reply_result = $wechatAdvancedInterface->customerService( $reply_array );
        if( $reply_result['code'] != 200 ){
            return array( 'code'=> 400 , 'message' => '发送消息失败');
        }

        return array( 'code'=> 200 , 'message' => 'ok', 'data' => $result , 'status'=>$seatStatusMessage['status'] );

    }

    /**
     *  客服退出坐席
     *
     * $arg_array = array(
     *  'wxID' => '1'                                   //微信ID
     *  'seatID' => '922D6B862C8F54F1E8775EE0A00F184F'  //客服坐席号
     * )
     */
    public function exitSeat($arg_array,$G_PGLOB){

        if( !isset($arg_array['wxID'],$arg_array['seatID'],$G_PGLOB) || empty($arg_array['seatID']) || empty($arg_array['wxID']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //检查客服坐席信息
        $check_array = array(
            'seatID' => $arg_array['seatID'],
            'wxID'   => $arg_array['wxID']
        );
        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB);

        if( $check_result['code'] != 200 ){
            return array( 'code' => $check_result['code'] , 'message' => $check_result['message'] );
        }

        //更新坐席状态
        $messageMangerObj=new messageManager($arg_array['wxID'],$arg_array['seatID']);
        $messageMangerObj->init($this->cacheObj);
        $seat_check=$messageMangerObj->getSeatStatsT();

        if (isset($seat_check)){
        	$new_seat_check=array();
        	$new_seat_check['status']=messageManager::SEAT_LOGOUT;
        	//$new_seat_check['userNumber']=0;
        	//$seat_check['status']=messageManager::SEAT_LOGOUT;
        	//$seat_check['userNumber']=0;
        	$messageMangerObj->setSeatStatsT($new_seat_check);
        	 
        }
        
        //获取坐席状态信息
        $seatStatusMessage = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'].'_'.$arg_array['seatID'],true);

        //获取当前登录用户的userID
        $userID = $G_PGLOB->currentUserID;

        //获取公众号下的坐席映射信息
        $getSeatMap = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'],true);

        //更新相关数据库信息
        try{

            //开启事务
            $this->dbca->beginTransaction();

            //第一步：更新客服退出时间
            $wechat_seat_log = new entity('wechat_seat_log');
            $wechat_seat_log->seatID  = $arg_array['seatID'];
            $wechat_seat_log->pcustID = $userID;
            $wechat_seat_log->wxID    = $arg_array['wxID'];

            if( $this->dbca->fetch($wechat_seat_log) ){

                $wechat_seat_log->exitTime = date('Y-m-d H:i:s');
                $this->dbca->save( $wechat_seat_log );

            }

            //第二步：解除库表中的映射关系
            $wechat_seat_service_map = new entity('wechat_seat_service_map');
            $wechat_seat_service_map->wxID    = $arg_array['wxID'];
            $wechat_seat_service_map->seatID  = $arg_array['seatID'];
            $wechat_seat_service_map->pcustID = $userID;

            if( $this->dbca->fetch($wechat_seat_service_map) ){

                $this->dbca->delete( $wechat_seat_service_map );

            }

            //第三步：将该公众号“可分配坐席数量”减1
            $wechat_wx_public = new entity('wechat_wx_public');
            $wechat_wx_public->wxID = $arg_array['wxID'];

            if( !$this->dbca->fetch( $wechat_wx_public ) ){
                throw new Exception('公众号信息没找到' , 404);
            }

            $wechat_wx_public->publicAllocatedNumber = $wechat_wx_public->publicAllocatedNumber-1;
            $this->dbca->save( $wechat_wx_public );

            //判断公众号“可分配坐席数量”
            $temp_array = array(
                'wxID' => $arg_array['wxID']  //公众号ID
            );
            $getPublicInfo = $this->searchWxPublic($temp_array);

            if( $getPublicInfo[0]['publicAllocatedNumber'] < 0 ){
                throw new Exception('系统错误，请稍后退出' , 400 );
            }

            //提交事务
            $this->dbca->commit();

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {

                error_log( $e->getMessage() );
                return array( 'code' => 500, 'message' => '系统错误，请稍后退出' );
            }

        }
	
        //第四步：解除redis绑定关系
        unset( $getSeatMap[$arg_array['seatID']] );
        $G_PGLOB->sessionCache_set( '__cs_seatList_'.$arg_array['wxID'] , $getSeatMap , 86400,true );

        return array( 'code' => 200 , 'message' => 'ok' );

    }

    /**
     *  客服服务记录
     *@params $arg_array = array()
     *@create by allen.qiang
     */
    public function serviceCountList(&$arg_array,$G_PGLOB){

        if( !isset($arg_array['createTime'],$arg_array['exitTime'],$G_PGLOB) || $arg_array['createTime'] > $arg_array['exitTime'] ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //sql字符串
        $sql = ' WHERE ';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //时间区间
        if (!empty($arg_array['createTime'])&&!empty($arg_array['exitTime'])&& $arg_array['exitTime'] > $arg_array['createTime']) {
            $sql .= ' wso.createTime between ? AND ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['createTime'];
            $params_array[] = $arg_array['exitTime'];
        }

        //通过客服名称获取客服ID
        if (isset($arg_array['custName']) && !empty($arg_array['custName'])) {
            $sql .= ' AND um.trueName LIKE ?';
            $params_type .= 's';
            $params_array[] =  '%' . trim($arg_array['custName']) . '%';
        }

        //通过公众号名称获取公众号ID
        if (isset($arg_array['wxName']) && !empty($arg_array['wxName'])) {
            $sql .= ' AND wwp.wxName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['wxName']) . '%';
        }

        try{
            //分页字符串
            $limit = '';

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $limit .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $limit .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $limit .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //统计数量
            $search_sql  = 'SELECT COUNT(*) AS num FROM `wechat_seat_log` wso INNER JOIN `wechat_wx_public` wwp ON wso.wxID=wwp.wxID LEFT JOIN `user_master` um ON wso.`pcustID` = um.`userID` ' . $sql;
            $count_array = $G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if( $count_array[0]->num == 0 ){
                $arg_array['count'] = 0;
                return null;
            }else{
                $arg_array['count'] = $count_array[0]->num;
                //查询分类信息
                $search_sql = 'SELECT wso.createTime,wso.exitTime,wso.logID,wwp.wxName,um.userID,um.trueName FROM `wechat_seat_log` wso
					  INNER JOIN `wechat_wx_public` wwp ON wso.wxID=wwp.wxID LEFT JOIN `user_master` um ON wso.`pcustID` = um.`userID` ' . $sql . $limit;
                $result = $G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

                //查询结果

                foreach($result as $data){
                    if($data->exitTime){
                        $readMessageCount = $G_PGLOB->DBCA->stmt_query('SELECT COUNT(*) AS num FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ? AND writeMessageTimeStamp < ?', 'sss', array($data->userID,$data->createTime,$data->exitTime));
                        $writeMessageCount = $G_PGLOB->DBCA->stmt_query('SELECT COUNT(*) AS num FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ? AND writeMessageTimeStamp < ? AND messageStatus = ?', 'sssi', array($data->userID,$data->createTime,$data->exitTime,3));
                        $writeMessageTime = $G_PGLOB->DBCA->stmt_query('SELECT MAX(writeMessageTimeStamp) lastTime FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ? AND writeMessageTimeStamp < ?', 'sss', array($data->userID,$data->createTime,$data->exitTime));
                    }else{
                        $readMessageCount = $G_PGLOB->DBCA->stmt_query('SELECT COUNT(*) AS num FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ?', 'ss', array($data->userID,$data->createTime));
                        $writeMessageCount = $G_PGLOB->DBCA->stmt_query('SELECT COUNT(*) AS num FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ? AND messageStatus = ?', 'ssi', array($data->userID,$data->createTime,3));
                        $writeMessageTime = $G_PGLOB->DBCA->stmt_query('SELECT MAX(writeMessageTimeStamp) lastTime FROM wechat_client_message_log WHERE pcustID = ? AND readMessageTimeStamp > ?', 'ss', array($data->userID,$data->createTime));
                    }
                    $result_array[] = array(
                        'createTime'            => $data->createTime,
                        'exitTime'              => $data->exitTime,
                        'wxName'                => $data->wxName,
                        'userID'                => $data->userID,
                        'trueName'              => $data->trueName,
                        'readMessageCount'     => $readMessageCount[0]->num,
                        'writeMessageCount'    => $writeMessageCount[0]->num,
                        'writeMessageTime'     => $writeMessageTime[0]->lastTime
                    );
                }
                return $result_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    //查询未读离线消息总数
    public function offLineMessage( &$arg_array ) {

        if(isset($arg_array['startDate'],$arg_array['endDate'])&&$arg_array['startDate'] > $arg_array['endDate']){
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //查询客户UUID
        if(isset($arg_array['custUuid']) && !empty($arg_array['custUuid'])){
            $sql .= ' AND custUuid = ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['custUuid'];
        }

        //消息状态
        if($arg_array['disposStatus'] == 1 || $arg_array['disposStatus'] == 2){
            $sql .= ' AND disposStatus = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['disposStatus'];

            //查询日期
            if(isset($arg_array['startDate'],$arg_array['endDate']) && !empty($arg_array['startDate'])&&!empty($arg_array['endDate'])&&$arg_array['startDate']<=$arg_array['endDate']){
                $sql .= ' AND messageTime BETWEEN ? AND ? ';
                $params_type .= 'ss';
                $params_array[] = $arg_array['startDate'] . ' 00:00:00';
                $params_array[] = $arg_array['endDate'] . ' 23:59:59';
            }
        }else if($arg_array['disposStatus'] == 3 ){


            if(isset($arg_array['messageStatus']) || empty($arg_array['messageStatus'])){  //查询所有离线消息
                $sql .= ' AND wcml.messageStatus = ? OR wcml.messageStatus = ? ';
                $params_type .= 'ii';
                $params_array[] = 5;
                $params_array[] = 8;
            }else{   //查询未锁定离线消息
                $sql .= ' AND wcml.messageStatus = ? ';
                $params_type .= 'i';
                $params_array[] = $arg_array['messageStatus'];
            }

            //查询日期
            if(isset($arg_array['startDate'],$arg_array['endDate']) && !empty($arg_array['startDate'])&&!empty($arg_array['endDate'])&&$arg_array['startDate']<=$arg_array['endDate']){
                $sql .= ' AND wcml.createTime BETWEEN ? AND ? ';
                $params_type .= 'ss';
                $params_array[] = $arg_array['startDate'] . ' 00:00:00';
                $params_array[] = $arg_array['endDate'] . ' 23:59:59';
            }

        }




        //流水号
//        if ( isset($arg_array['disposID']) && is_numeric($arg_array['disposID']) ) {
//            $sql .= ' AND disposID = ?';
//            $params_type .= 'i';
//            $params_array[] = $arg_array['disposID'];
//        }
//
//        //会员号
//        if ( isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID']) ) {
//            $sql .= ' AND pcustID = ?';
//            $params_type .= 'i';
//            $params_array[] = $arg_array['pcustID'];
//        }
//
//        //会员昵称号
//        if ( isset($arg_array['userName']) && !empty($arg_array['userName']) ) {
//            $sql .= ' AND userName LIKE ?';
//            $params_type .= 's';
//            $params_array[] = $arg_array['userName'];
//        }
//
//        //客服名称
//        if ( isset($arg_array['trueName']) && !empty($arg_array['trueName']) ) {
//            $sql .= ' AND trueName LIKE ?';
//            $params_type .= 's';
//            $params_array[] = $arg_array['trueName'];
//        }



        if ( $sql ) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                if($arg_array['disposStatus'] == 1 || $arg_array['disposStatus'] == 2){
                    $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_client_offLineMessage_log  ' . $sql;

                }else if($arg_array['disposStatus'] == 3){
                    $search_sql = 'SELECT COUNT(DISTINCT wcml.openId) AS item_count FROM log_customerservice_message AS wcml
                    LEFT JOIN wechat_user_record AS wur ON wcml.openId = wur.openId ' . $sql ;
                    $sql .= sprintf(' GROUP BY wcml.openId ');
                }

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            if($arg_array['disposStatus'] == 1 || $arg_array['disposStatus'] == 2){
                $search_sql_dispos = 'SELECT wcol.*,wur.userName FROM wechat_client_offLineMessage_log AS wcol
                LEFT JOIN wechat_user_record AS wur ON wcol.openId = wur.openId' . $sql;

            }else if($arg_array['disposStatus'] == 3){
                $search_sql_log = 'SELECT wcml.openId,wcml.custUuid,wcml.messageStatus,MAX(wcml.createTime) AS createTime,COUNT(wcml.logID) AS messageNum,wur.userName FROM log_customerservice_message AS wcml
                LEFT JOIN wechat_user_record AS wur ON wcml.openId = wur.openId ' . $sql;

            }

            //信息处理表
            if(isset($search_sql_dispos)&&!empty($search_sql_dispos)){

                $temp_item_array = &$this->dbca->stmt_query($search_sql_dispos, $params_type, $params_array);

                if($arg_array['disposStatus'] == 1 || $arg_array['disposStatus'] == 2){
                    if (!$temp_item_array)
                        return null;
                    foreach($temp_item_array as &$item) {

                        $item_array[] = array(
                            'disposID' 	         => $item->disposID,
                            'openId'                => $item->openId,
                            'messageNum'            => $item->messageNum,
                            'userName' 	         => $item->userName,
                            'messageTime' 	         => $item->messageTime,
                            'seatID' 	             => $item->seatID,
                            'trueName' 	         => $item->trueName,
                            'disposTimeStamp' 	 => $item->disposTimeStamp,
                            'timeStamp' 	         => $item->timeStamp,
                            'disposStatus' 	     => $item->disposStatus
                        );

                    }

                    return $item_array;

                }

            }

            //信息处理表
            if(isset($search_sql_log)&&!empty($search_sql_log)){
                $temp_item_array_log = &$this->dbca->stmt_query($search_sql_log, $params_type, $params_array);

                if (!$temp_item_array_log &&$arg_array['disposStatus'] == 3)
                    return null;

                if($arg_array['disposStatus'] == 3){
                    foreach($temp_item_array_log as &$item) {

                        $item_array[] = array(
                            'disposID' 	         => '',
                            'openId'                => $item->openId,
                            'uuid'                  => $item->custUuid,
                            'messageNum'            => $item->messageNum,
                            'userName' 	         => $item->userName,
                            'messageTime' 	         => $item->createTime,
                            'messageStatus' 	     => $item->messageStatus,
                            'seatID' 	             => '',
                            'trueName' 	         => '',
                            'disposTimeStamp' 	 => '',
                            'disposStatus' 	     => 3
                        );

                    }
                    return $item_array;
                }
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    //更改离线消息记录表状态和添加离线消息处理表数据
    public function operateDb(&$arg_array){


        try{

            //查询离线消息条数
            $arg_array['messageStatus'] = 5; //离线消息
            $result_array = $this->offLineMessage($arg_array);

            //保存和更新消息处理记录
            $public = new entity('wechat_client_offLineMessage_log');

            if(!empty($result_array['disposID'])&&$result_array['disposID'] > 0 ){

                $public->disposID	= $arg_array['disposID'];

                if( !$this->dbca->fetch($public) ){
                    return array( 'code'=>404 , 'message'=>'没有找到信息' );
                }

            } else {
                global $G_PGLOB;
                $public->creator	= $G_PGLOB->currentUserName;
            }

            $public->messageNum  	    = $result_array[0]['messageNum'];
            $public->openId       	    = $result_array[0]['openId'];
            $public->userName  	    = $result_array[0]['userName'];
            $public->messageTime  	    = $result_array[0]['messageTime'];
            $public->disposTimeStamp  = date('Y-m-d H-i-s',time());
            $public->seatID  	        = $arg_array['seatID'];


            //查询客服信息
            if(!empty($arg_array['seatID'])){
                $search_sql = 'SELECT um.trueName FROM wechat_seat_log AS wsl
                LEFT JOIN user_master AS um
                ON wsl.pcustID = um.userID
                WHERE wsl.seatID = ? ';
                $trueName_array = $this->dbca->stmt_query($search_sql, 's', array($arg_array['seatID']));

                if( !$trueName_array ){
                    return array( 'code'=>404 , 'message'=>'没有找到客服信息' );
                }
                $trueName = $trueName_array[0]->trueName;
            }
            $public->trueName  	    = $trueName;
            $public->disposStatus  	= 1;

            if(!empty($result_array[0]['openId'])){
                $this->dbca->save( $public ) ;
            }

            //消息记录表更改状态（锁定状态改为已回复状态）
            $search_sql = 'UPDATE log_customerservice_message SET messageStatus = 7 WHERE custUuid = ? AND messageStatus = 8 ';

            $result = $this->dbca->stmt_query($search_sql,'s',array($arg_array['custUuid']));
            if($result){
                return array( 'code' => 200, 'message' => '保存成功');
            }

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }


    /**
     *  获取坐席客户离线消息（离线回复页面查询）
     *
     * $arg_array = array(
     * 'seatID' => 'fsdfsad9897685sdnfjsd'  //客服坐席号(UUID)
     * 'wxID' => 'fsdfsad9897685sdnfjsd'    //公众号ID
     * 'uuid' => 'fsdfsad9897685sdnfjsd'    //公众号ID
     * )
     */
    public function getSeatOffMessage($arg_array,$G_PGLOB){

        if( !isset($arg_array['seatID'],$arg_array['wxID'],$arg_array['uuid']) || empty($arg_array['seatID']) || !is_numeric($arg_array['wxID']) ){
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //检查客服坐席信息
        $check_array = array(
            'seatID' => $arg_array['seatID'],
            'wxID'   => $arg_array['wxID']
        );

        $check_result = $this->checkServiceSeat($check_array,$G_PGLOB);

        if( $check_result['code'] != 200 ){
            return array( 'code' => $check_result['code'] , 'message' => $check_result['message'] );
        }

        //获取坐席状态信息
        $seatStatusMessage = $G_PGLOB->sessionCache_get('__cs_seatList_'.$arg_array['wxID'].'_'.$arg_array['seatID'],true);

        //读取坐席离线消息
        $messageObj=new messageManager($arg_array['wxID'],$arg_array['seatID']);
        $messageObj->init($this->cacheObj);
        $messageObj->setProcessMessageMode(messageManager::OFFLINE);
        $params = array($arg_array['uuid']);
        $result = $messageObj->readMessage($params);

        return array( 'code'=> 200 , 'message' => 'ok', 'data' => $result , 'status'=>$seatStatusMessage['status'] );

    }

    //保存工作时间
    public function workTimeSave($arg_array){

        //检查参数是否完整
        if(!isset($arg_array['serviceStartTime'],$arg_array['serviceEndTime'])||$arg_array['serviceStartTime'] >$arg_array['serviceEndTime']){
            return array( 'code'=>400 , 'message'=>'参数错误，请与管理员联系' );
        }

        //连接错误信息的字符串
        $error_msg = '';

        if(empty($arg_array['serviceStartTime'])){
            $error_msg .= '客服上线时间不能为空<br>';
        }

        if( empty($arg_array['serviceEndTime']) ){
            $error_msg .= '代金卡类型不能为空<br>';
        }

        if($arg_array['serviceStartTime'] >$arg_array['serviceEndTime'] ){
            $error_msg .= '上线时间必须小于下线时间<br>';
        }

        if( $error_msg != '' )
            return array( 'code'=>400 , 'message'=>$error_msg );

        try{

            //事务开启
            $this->dbca->beginTransaction();

            $workTime = new entity('wechat_customerService_worktime');
            $workTime->timeID = 1;
            $this->dbca->fetch($workTime);
            $workTime->creator = $arg_array['creator'];
            $workTime->work_startTime = $arg_array['serviceStartTime'] ;
            $workTime->work_endTime = $arg_array['serviceEndTime'];

            //保存信息
            $this->dbca->save($workTime);

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'更新成功');

        }catch(Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            }else{

                error_log($e->getMessage());
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

            }

        }
    }

    //查询客服上下班时间
    public function searchWorkTime(){
        $result = $this->dbca->stmt_query('SELECT * FROM wechat_customerService_worktime WHERE timeID = ?','i',array(1));
        if(!$result){
            return null;
        }
        $result_array = array(
            'serviceStartTime'  =>$result[0]->work_startTime,
            'serviceEndTime'    =>$result[0]->work_endTime
        );
        return $result_array;
    }


}